/*
To implement a circularly linked list.
Program by Thomas Jacob & Syam Kumar
26 February,2001
*/

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

typedef struct node item;
struct node
{
 int data;
 item * next;
};

item *start;
int isempty=1;

void msg(char *s)
{
 int i;

 printf("\t%s",s);
 getch();
 for(i=0;i<strlen(s);i++)
  printf("\b \b");
}

item* findparent(int value)
{
 int found=0;
 item *cursor,*save;

 cursor=start;
 do
 {
  if(cursor->next->data==value) found=1;
  if(found) save=cursor;
  cursor=cursor->next;
 }while(cursor!=start && !found);

 if(!found) {msg("Not found."); return(0);}
 else return(save);
}

item* add()
{
 char cont;
 item *insloc,*new;
 int value,search;

 do
 {
  printf("\nData: ");   scanf("%d",&value);
  if(isempty)
   {
    start=(item*)malloc(sizeof(struct node));
    start->data=value;
    start->next=start;
    new=start;
    isempty=0;
   }
  else
   {
    gotoxy(25,wherey()-1);
    printf("Insert after: "); scanf("%d",&search);
    insloc=findparent(search);
    if(insloc)
     {
      new=(item *)malloc(sizeof(struct node));
      new->data=value;
      new->next=insloc->next;
      insloc->next=new;
      if(insloc->next==start) start=new;
     }
    }
  gotoxy(50,wherey()-1);
  printf("Continue<Y/N>? ");
  cont=toupper(getche());
 } while(cont!='N');
 return(new);
}

int view()
{
 item *temp=start;

 if(isempty)
  {
   printf("<EMPTY>");
   return(0);
  }
 do
 {
  printf("%d\t",temp->data);
  temp=temp->next;
 }while(temp!=start);
}

void delete(item *curr)
{
 item* pos;
 int value;

 printf("Value to delete: ");
 scanf("%d",&value);
 pos=findparent(value);
 if(pos)
  {
   if(start->next==start) isempty=1;
   if(pos->next==start) start=start->next;
   if(pos->next==curr) curr=pos->next->next;
   pos->next=pos->next->next;
  }
}

void main()
{
 char choice;
 item *curr;

 do
 {
   clrscr();
   printf("---CIRCULAR LINKED LIST----\n");
   printf("Contents : ");
   view();
   printf("\n\n<I> . . . Insert\n");
   printf("<D> . . . Delete\n");
   printf("<X> . . . Exit\n\n");
   printf("Choice: ");
   choice=toupper(getche());
   printf("\n");
   switch(choice)
   {
    case 'I':curr=add();
	     break;
    case 'D':if(isempty) msg("List empty.");
	     else delete(curr);
	     break;
    case 'V':if(isempty) msg("List empty.");
	     else view(curr);
	     break;
   }
 }while(choice!='X');
}

